<template>
  <a-card title="节点信息" size="small" class="property-panel" ref="propertyPanel">
    <a-form :form="form" :labalCol="{span:3}" size="small">
      <a-form-item label="节点ID" :hidden="true">
        <a-input v-model="form.id" disabled></a-input>
      </a-form-item>
      <a-form-item label="节点名称">
        <a-input v-model="form.name" @change="nameChange" disabled></a-input>
      </a-form-item>
      <!-- <a-form-item label="节点颜色">
        <a-color-picker v-model="form.color" @change="colorChange"></a-color-picker>
      </a-form-item>-->
      <!-- 任务节点允许选择人员 -->
      <a-form-item label="节点人员" v-if="userTask" v-show="false">
        <a-select v-model="form.userType" placeholder="请选择" @change="typeChange">
          <a-select-option value="assignee">指定人员</a-select-option>
          <a-select-option value="candidateUsers">候选人员</a-select-option>
          <a-select-option value="candidateGroups">角色/岗位</a-select-option>
          <a-select-option value="teams">团队人员</a-select-option>
        </a-select>
      </a-form-item>
      <!-- 指定人员 -->
      <a-form-item label="指定人员" v-if="userTask && form.userType === 'assignee'">
        <a-select
          v-model="form.assignee"
          placeholder="请选择"
          key="1"
          optionFilterProp="children"
          :showSearch="true"
          @change="(value) => addUser({assignee: value})"
        >
          <a-select-option v-for="item in users" :key="item.id" :value="item.id">{{item.username}}</a-select-option>
        </a-select>
      </a-form-item>
      <!-- 候选人员 -->
      <a-form-item label="候选人员" v-else-if="userTask && form.userType === 'candidateUsers'">
        <a-select
          v-model="form.candidateUsers"
          placeholder="请选择"
          key="2"
          mode="multiple"
          optionFilterProp="children"
          :showSearch="true"
          @change="(value) => addUser({candidateUsers: value.join(',') || value})"
        >
          <a-select-option v-for="item in users" :key="item.id" :value="item.id">{{item.username}}</a-select-option>
        </a-select>
      </a-form-item>
      <!-- 角色/岗位 -->
      <a-form-item label="角色/岗位" v-else-if="userTask && form.userType === 'candidateGroups'">
        <a-select
          v-model="form.candidateGroups"
          placeholder="请选择"
          key="3"
          optionFilterProp="children"
          :showSearch="true"
          @change="(value) => addUser({candidateGroups: value})"
        >
          <a-select-option v-for="item in roles" :key="item.id" :value="item.id">{{item.roleName}}</a-select-option>
        </a-select>
      </a-form-item>

      <!--      &lt;!&ndash; 团队名称&ndash;&gt;-->
      <!--      <a-form-item label="团队名称" v-else-if="userTask && form.userType === 'teams'">-->
      <!--        <a-select-->
      <!--          v-model="form.teamName"-->
      <!--          placeholder="请选择"-->
      <!--          key="4"-->
      <!--          optionFilterProp="children"-->
      <!--          :showSearch="true"-->
      <!--          @change="(value) => updateTeams({teamName: value})"-->
      <!--        >-->
      <!--          <a-select-option v-for="item in teams" :key="item.id" :value="item">{{item.teamName}}</a-select-option>-->
      <!--        </a-select>-->
      <!--      </a-form-item>-->

      <!--      &lt;!&ndash; 团队成员&ndash;&gt;-->
      <!--      <a-form-item label="团队成员" v-if="userTask && form.userType === 'teams' ">-->
      <!--        <a-select v-model="form.teamPlayer" placeholder="请选择"-->
      <!--                  optionFilterProp="children"-->
      <!--                  key="5"-->
      <!--                  :showSearch="true"-->
      <!--                  @change="(value) =>updateTeamPlayers({teamPlayer: value})"-->
      <!--        >-->
      <!--          <a-select-option v-for="(item,index) in teamPlayers" :key="index" :value="item">{{item}}-->
      <!--          </a-select-option>-->
      <!--        </a-select>-->
      <!--      </a-form-item>-->
      <!-- 定义节点描述-->
      <a-form-item label="节点描述" v-if="userTask">
        <a-textarea placeholder="请对该节点进行描述"
                    v-model="description"
                    @change="descriptionChange"
                    :rows="4"></a-textarea>
      </a-form-item>
      <!-- 定义输入输入格式-->
      <a-form-item label="输入格式" v-if="userTask" v-show="false">
        <a-select
          placeholder="请选择"
          key="2"
          mode="multiple"
          v-model="form.inputFormat"
          @change="(value) => addInputFormat({inputFormat: value.join(',') || value})"
        >
          <a-select-option v-for="item in fileFormat" :key="item" :value="item">{{item}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 定义输入输出格式-->
      <a-form-item label="输出格式" v-if="userTask">
        <a-select
          placeholder="请选择"
          key="2"
          mode="multiple"
          v-model="form.outputFormat"
          @change="(value) => addOutputFormat({outputFormat: value.join(',') || value})"
        >
          <a-select-option v-for="item in fileFormat" :key="item" :value="item">{{item}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!--     &lt;!&ndash;添加任务节点开始时间和结束时间&ndash;&gt;-->
      <!--   <a-form-item  label="计划开始时间" v-if="userTask">
           <a-date-picker
             :disabled="readOnly"
             placeholder="计划开始时间"
             v-model="startTime"
             @change="startChange"
             type="date"
             show-time
             :format="dateFormat"
             :getCalendarContainer="getCalendarContainer"
           />
         </a-form-item>

         <a-form-item  label="计划结束时间" v-if="userTask">
           <a-date-picker
             :disabled="readOnly"
             placeholder="计划结束时间"
             v-model="endTime"
             @change="endChange"
             type="date"
             show-time
             :format="dateFormat"
             :disabledDate="disabledDateHandler"
             :getCalendarContainer="getCalendarContainer"
           />
         </a-form-item>
   -->

      <!-- 分支允许添加条件 -->
      <a-form-item label="分支条件" v-if="sequenceFlow">
        <a-select v-model="form.user" placeholder="请选择">
          <a-select-option v-for="item in users" :key="item.id" :title="item.id">{{item.username}}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
  import {getUserList, getRoleList} from '@/api/api'
  import {teamall, getTeamList} from '@/api/team'
  import moment from 'moment'

  export default {
    name: 'PropertyPanel',
    props: {
      modeler: {
        type: Object,
        required: true
      },
      value: {
        type: String,
        required: false
      }
    },
    computed: {
      userTask() {
        if (!this.element) {
          return
        }
        return this.element.type === 'bpmn:UserTask'
      },
      sequenceFlow() {
        if (!this.element) {
          return
        }
        return this.element.type === 'bpmn:SequenceFlow'
      }
    },
    data() {
      let dateStr = this.value;
      return {
        decorator: "",
        // momVal:!dateStr?null:moment(dateStr,this.dateFormat),
        form: this.$form.createForm(this),
        model: {
          id: '',
          name: '',
          color: null
        },
        element: {},
        users: [],   //用户列表的数据
        roles: [],  //角色行列的数据
        teams: [],   //团队名称的数据
        teamPlayers: [],    //团队成员遍历团队名称，根据名称来显示此团队的成员
        fileFormat: ['.dll', '.txt', '.xlsx', '.docx', '.rar'],
        activityId: "",
        name: "",
        inputFileTypeArray: [],
        outputFileTypeArray: [],
        description: '',
        descriptionArray: []
      }
    },
    mounted() {
      this.loadRoles()
      this.loadUsers()
      this.handleModeler()
      this.loadTeams()
    },
    methods: {
      clearFields() {
        this.outputFileTypeArray = []
        this.descriptionArray = []
        this.form.resetFields()
      },
      initData() {
        this.loadRoles()
        this.loadUsers()
        this.loadTeams()
      },
      loadUsers() {
        const vm = this
        getUserList().then(res => {
          vm.users = [].concat(res.result.records)
        })
      },
      loadRoles() {
        const vm = this
        getRoleList().then(res => {
          vm.roles = [].concat(res.result.records)
        })
      },
      loadTeams() {
        const vm = this
        getTeamList().then(res => {
          vm.teams = [].concat(res.result.records)
        })
      },
      handleModeler() {
        // 监听节点选择变化
        this.modeler.on('selection.changed', this.selectionChanged)

        //  监听节点属性变化
        this.modeler.on('element.changed', this.elementChanged)
      },
      selectionChanged(e) {

        const element = e.newSelection[0]
        this.element = element
        if (!element) return
        this.form = {
          ...element.businessObject,
          ...element.businessObject.$attrs
        }
        if (this.form.userType === 'candidateUsers') {
          this.form['candidateUsers'] = this.form['candidateUsers'].split(',') || []
        }
        if (this.form.outputFormat != null) {
          let outputFormat = this.form.outputFormat;
          this.form.outputFormat = typeof outputFormat == 'string' ? outputFormat.split(',') : outputFormat;
        }
      },
      elementChanged(e) {
        const {element} = e
        this.activityId = element.id
        if (!element) return
        //  新增节点需要更新回属性面板
        if (element.id === this.form.id) {
          this.form.name = element.businessObject.name
          this.form = {...this.form}
        }

      },
      // 属性面板名称，更新回流程节点
      nameChange(e) {
        // let name = e.target.value
        let name = this.form.name
        const modeling = this.modeler.get("modeling");
        modeling.updateLabel(this.element, name);
      },

      //根据团队名称添加团队成员
      updateTeams(properties) {
        let that = this;
        this.teams.forEach(function (item) {
          if (item.id == properties.teamName.id) {
            that.teamPlayers = item.teamPlayer.split(",");
          }
        })
        this.updateProperties(Object.assign({teamName: properties.teamName.teamName}, {
          userType: "teams"
        }))
      },
      updateTeamPlayers(properties) {
        this.updateProperties(
          Object.assign(properties, {
            userType: "teams"
          })
        )
      },
      // 任务节点配置人员
      addUser(properties) {
        this.updateProperties(
          Object.assign(properties, {
            userType: Object.keys(properties)[0]
          })
        )
      },
      // 切换人员类型
      typeChange() {
        const types = ['assignee', 'candidateUsers', 'candidateGroups', 'teams']
        types.forEach(type => {
          delete this.element.businessObject.$attrs[type]
          delete this.form[type]
        })
      },
      // 在这里我们封装一个通用的更新节点属性的方法
      updateProperties(properties) {
        const modeling = this.modeler.get('modeling')
        modeling.updateProperties(this.element, properties)
      },
      addInputFormat(properties) {
        let that = this
        this.updateProperties({})
        Object.assign(properties, {activityId: that.activityId})

        let index = 0
        let bool = false
        that.inputFileTypeArray.forEach((val, key) => {
          if (val.activityId === that.activityId) {
            bool = true
            index = key
          }
        })

        if (bool) {
          that.inputFileTypeArray.splice(index, 1, properties)
        } else {
          that.inputFileTypeArray.push(properties)
        }

        this.$emit('inputFileType', that.inputFileTypeArray)
      },
      addOutputFormat(properties) {
        console.info(properties)
        this.updateProperties(properties)
        let name = this.form.name;
        let actExistIdx = this.outputFileTypeArray.findIndex(item => item.activityId == this.activityId);
        if (actExistIdx != -1) {
          if (typeof properties.outputFormat == "string") {
            this.outputFileTypeArray[actExistIdx].outputFormats = properties.outputFormat;
          } else {
            this.outputFileTypeArray.splice(actExistIdx, 1);
          }
        } else {
          this.outputFileTypeArray.push({
            activityId: this.activityId,
            outputFormats: properties.outputFormat,
            name: name
          })
        }

        /*
        Object.assign(properties, {activityId: this.activityId})
        let index = 0
        let bool = false
        this.outputFileTypeArray.forEach((val, key) => {
           if (val.activityId === this.activityId) {
             bool = true
             index = key
           }
         })

         if (bool) {
           this.outputFileTypeArray.splice(index, 0, properties)
         } else {
           this.outputFileTypeArray.push(properties)
         }*/
        console.info(this.outputFileTypeArray)
        this.$emit('outputFileType', this.outputFileTypeArray)
      },
      descriptionChange(e) {
        let value = e.target.value;
        let name = this.form.name;
        this.updateProperties({})
        let index = this.descriptionArray.findIndex(item => item.activityId == this.activityId)
        if (index == -1) {
          this.descriptionArray.push({
            description: value,
            activityId: this.activityId,
            name: name
          })
        } else {
          this.descriptionArray[index].description = value
        }
        this.$emit('descriptionType', this.descriptionArray)
      }
      // 更新时间描述
      /*      moment,
            startChange(date){
              let value = this.moment(date).format(this.dateFormat);
              this.updateProperties({})
              let index = this.startArray.findIndex(item=>{
                return item.activityId ==this.activityId
              })
              if(index==-1){
                this.startArray.push({
                  startTime: value,
                  activityId: this.activityId
                })
              }else{
                this.startArray[index].startTime = value
              }
              this.$emit('startType', this.startArray)
            },
            disabledDateHandler(date) {
               return date && date < this.startTime.endOf('day')
            },
            endChange(date){
                let value = this.moment(date).format(this.dateFormat);
                this.updateProperties({})
                let index = this.endArray.findIndex(item=>{
                  return item.activityId ==this.activityId
                })
                if(index==-1){
                  this.endArray.push({
                    endTime: value,
                    activityId: this.activityId
                  })
                }else{
                  this.endArray[index].endTime = value
                }
                this.$emit('endType', this.endArray)
              }*/

    }
  }
</script>

<style lang="scss" scoped>


  .property-panel {
    position: absolute;
    right: 10px;
    top: 60px;
    padding: 20px 0;
    width: 220px;
    height: 710px;
    background:#ECF4FF ;
  }

  .ant-card-bordered {
    border: 1px solid #ECF4FF;
  }

</style>
